package com.qin.EducationalManger.user.dao;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.qin.EducationalManger.user.model.UserModel;
import com.qin.EducationalManger.utils.JdbcUtils;


public class UserDao {
	JdbcUtils jdbcUtils = new JdbcUtils();

	public static int insert(UserModel model) {

		String sql = "insert into user (account,password,teacher_id) values(?,?,?)";
		
		List<Object> vals = Arrays.asList(model.getAccount(), model.getPassword(), model.getTeacherId());
        
		return JdbcUtils.update(sql, vals);

	}

	public static int delet(UserModel mode) {
		String sql = "delet from user where account like";
		List<Object> vals = Arrays.asList(mode.getAccount());

		return JdbcUtils.update(sql, vals);

	}
	
	//按照条件修改

	public static int update(UserModel mode) {

		StringBuffer sql = new StringBuffer("update user set id=id"); // 储存sql语句
		List<Object> vals = new ArrayList<Object>(); // 用于存储 要修改的 内容

	     // 账户不可以修改，只读
		String password = mode.getPassword();
		if (password != null&&password.intern().isEmpty()==false) {
			sql.append(",password = ?");
			vals.add(password);

		}
		String teacherId = mode.getTeacherId();
		if (teacherId != null && teacherId.intern().isEmpty() == false) {
			sql.append(",teacher_id = ?");
			vals.add(teacherId);
		}

		
		sql.append("where account = ?" + mode.getAccount());

		return JdbcUtils.update(sql.toString(), vals);

	}
	
	//按照条件查询
	public  static List<UserModel> select(UserModel model) {
	StringBuffer sql = new StringBuffer("select * from user where 1=1 ");
	
	Map<String, String> fields = new HashMap<String, String>();
	
	fields.put("account", "account");
	fields.put("password", "password");
	
	fields.put("teacherId", "teacher_id");

	
	
	String account =  model.getAccount();
	
	List<Object> vals = appendWhere(sql, model);
	
	
	return  JdbcUtils.Query(sql.toString(), vals, UserModel.class, fields);
	
	   
		
	}
	
	private static List<Object>  appendWhere(StringBuffer sql, UserModel model) {
		
		List<Object> vals = new ArrayList<Object>();
		String account = model.getAccount();
		if(account!=null&&account.intern().isEmpty()==false) {
			sql.append(" and account=?");
			vals.add(account);
		}
        
				
		String teacherId = model.getTeacherId();
		if(teacherId!=null&&teacherId.intern().isEmpty()==false) {
			
			sql.append(" and teacher_id =?");
			vals.add(teacherId);
		}
		
		return vals;
		
		
	}

}
